package com.icez.base_compose_framework

import android.content.Context
import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.icez.base_compose_framework.util.BNetworkUtil

sealed class Screen(val route:String){
    object Home:Screen("home")
    object Player:Screen("player/{$ARG_EPISODE_URI}"){
        fun createRoute(episodeUri:String) = "player/$episodeUri"
    }

    object PodcastDetails: Screen("podcast/{$ARG_PODCAST_URI}"){
        val PODCAST_URI = "podcastUri"
        fun createRoute(podcastUri: String) = "podcast/$podcastUri"
    }

    companion object{
        val ARG_PODCAST_URI = "podcastUri"
        val ARG_EPISODE_URI = "episodeUri"
    }
}

@Composable
fun RememberAppState(
    navController:NavHostController = rememberNavController(),
    context: Context = LocalContext.current
) = remember(navController,context){
    AppState(navController,context)
}

class AppState(val navController: NavHostController,private val context:Context){
    var isOnline by mutableStateOf(BNetworkUtil.isNetworkAvailable(context))
        private set

    fun refreshOnline(){
        isOnline =  BNetworkUtil.isNetworkAvailable(context)
    }

    fun navigateToPlayer(episodeUri: String,from:NavBackStackEntry){
        if (from.lifecycleIsResumed()){
            val encodedUri = Uri.encode(episodeUri)
            navController.navigate(Screen.Player.createRoute(encodedUri))
        }
    }

    fun navigateToProdcastDetails(podcastUri:String,from:NavBackStackEntry){
        if(from.lifecycleIsResumed()){
            val encodedUri = Uri.encode(podcastUri)
            navController.navigate(Screen.PodcastDetails.createRoute(encodedUri))
        }
    }

    fun navigateBack(){
        navController.popBackStack()
    }


}

private fun NavBackStackEntry.lifecycleIsResumed() =this.lifecycle.currentState == Lifecycle.State.RESUMED